import base64
import logging

from elasticsearch import Elasticsearch
from flask import Flask, abort, jsonify
from flask import request

app = Flask(__name__)
# 日志打印
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("flask-common.log")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)

logger.addHandler(handler)
logger.addHandler(console)


# 截获所有请求
@app.before_request
def before_request():
    ip = request.remote_addr
    url = request.url
    logger.info('访问信息: ip:%s url:%s' % (ip, url))


# mysql-manual search api包装
@app.route('/mysql-manual/search', methods=['GET', 'POST'])
def search():
    es = Elasticsearch('127.0.0.1:9200')
    index_name = 'mysql-manual'
    keyword = request.args.get('keyword')
    from_ = request.args.get('from')
    size = request.args.get('size')
    if from_ is None:
        from_ = 1
    if size is None:
        size = 10
    if keyword is not None and from_ is not None and size is not None:
        count_body = {
            "query": {
                "bool": {
                    "should": [
                        {
                            "match": {
                                "filename": {
                                    "query": keyword,
                                    "operator": "and"
                                }
                            }
                        },
                        {
                            "match": {
                                "content": {
                                    "query": keyword,
                                    "operator": "and"
                                }
                            }
                        },
                        {
                            "match": {
                                "title": {
                                    "query": keyword,
                                    "operator": "and"
                                }
                            }
                        }
                    ]

                }
            },
            "from": from_,
            "size": size
        }
        result = es.search(index=index_name, body=count_body)
        return jsonify(result)
    else:
        abort(400)


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8084)
